﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using yq.IBase;
using yq.CacheHelp;
using yq.Business;
using System.IO;
using yq.Model.Logic;
using System.Web;

namespace BLOB.Controllers
{
    /// <summary>
    /// fileid=[服务Id]_[文件夹ID]_[YYYYMMdd]_[文件ID]
    /// </summary>
    public class FileController : ApiController
    {
        [AcceptVerbs("post")]
        public string Add(string folderId, string filename, string extension)
        {
            var stream = HttpContext.Current.Request.InputStream;
            byte[] value = new byte[stream.Length];
            stream.Read(value, 0, value.Length);
            stream.Seek(0, SeekOrigin.Begin);
            string fileId = "";
            Func<DbHelper, CaCheRefresh, string> fun = (db, cb) =>
            {
                var dal = new SysFolderDal();
                var info = dal.Where(obj => obj.FolderId == folderId).ToModel(db);
                var server = new SysFileServerDal().Where(obj => obj.Sid == info.Sid).ToModel(db);
                var file = new SysFile()
                {
                    FileName = filename,
                    FileSize = value.Length / 1000,
                    UpTime = DateTime.Now,
                    FolderId = folderId,
                    IsDel = yq.Enums.BooleanType.No,
                    Sid = info.Sid,
                    Extension = extension
                };
                fileId = info.Sid + "_" + folderId + "_" + file.UpTime.ToString("yyyyMMdd") + "_" + "Guid".ExtNewGuid() + "." + extension;
                string path = server.Path + "\\" + folderId + "\\" + file.UpTime.ToString("yyyyMMdd") + "\\";
                Directory.CreateDirectory(path);
                path = path + fileId;
                new SysFileDal().Add(file, fileId, db);
                db.Commit();
                return path;
            };
            var savePath = DbExec.DoTrans(fun);
            using (FileStream sw = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                sw.Write(value, 0, value.Length);
            }

            return fileId;
        }

        [AcceptVerbs("post")]
        public bool Edit(string fileid)
        {
            var stream = HttpContext.Current.Request.InputStream;
            byte[] value = new byte[stream.Length];
            stream.Read(value, 0, value.Length);
            stream.Seek(0, SeekOrigin.Begin);
            Func<DbHelper, CaCheRefresh, string> fun = (db,cache) =>
            {
                var dal = new SysFileDal();
                var fileinfo = dal.Where(obj => obj.FileId == fileid).ToModel(db);
                dal.Update(fileinfo, db);

                var files = fileid.Split(char.Parse("_"));
                var serverdal = new SysFileServerDal();
                var info = serverdal.Where(obj => obj.Sid == files[0].ToString()).ToModel(db, yq.IBase.Basis.RowLock.False);

                return info.Path + "\\" + files[1] + "\\" + files[2] + "\\" + fileid;
            };
            var path = DbExec.DoTrans(fun);

            using (FileStream sw = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                sw.Write(value, 0, value.Length);
            }

            return true;
        }

        [AcceptVerbs("post")]
        public string Ver(string fileid)
        {
            Func<DbHelper, string> fun = (db) =>
            {
                var dal = new SysFileDal();
                return dal.Where(obj => obj.FileId == fileid).ToModel(db).Version;
            };
            return DbExec.DoRead(fun);
        }

        [AcceptVerbs("post")]
        public bool Del(string fileid)
        {
            Func<DbHelper, CaCheRefresh, bool> fun = (db, cb) =>
            {
                var dal = new SysFileDal();
                var info = dal.Where(obj => obj.FileId == fileid).ToModel(db);
                info.IsDel = yq.Enums.BooleanType.Yes;
                var b = dal.Update(info, db) == 1;
                db.Commit();
                return b;
            };

            return DbExec.DoTrans(fun);
        }

        [AcceptVerbs("post")]
        public byte[] Get(string fileid)
        {
            Func<DbHelper, string> fun = (db) =>
            {
                var files = fileid.Split(char.Parse("_"));
                var serverdal = new SysFileServerDal();
                var info = serverdal.Where(obj => obj.Sid == files[0].ToString()).ToModel(db, yq.IBase.Basis.RowLock.False);

                return info.Path + "\\" + files[1] + "\\" + files[2] + "\\" + fileid;
            };
            var path = DbExec.DoRead(fun);

            byte[] bt = new byte[1];
            using (System.IO.FileStream sm = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read))
            {
                bt = new byte[sm.Length];
                sm.Read(bt, 0, bt.Length);
            }

            return bt;
        }

    }
}